/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rpc.extension.context;

import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.core.context.ICAFContextService;
import io.iec.edp.caf.rpc.api.entity.RpcContext;
import io.iec.edp.caf.rpc.api.spi.RpcContextTransmittee;
import io.iec.edp.caf.tenancy.api.context.RequestTenantContextHolder;
import io.iec.edp.caf.tenancy.api.context.RequestTenantContextInfo;
import lombok.var;

public class TenantTransmitter implements RpcContextTransmittee {
    public static final String TENANTID = "transmitte-tenantid";
//    public static final String CHECK_CURRENT_TENANTID = "transmitte-check-current-tenantid";
    @Override
    public String identify() {
        return TransmitteType.TENANT.getValue();
    }

    @Override
    public RpcContext capture() {
        RpcContext context = RpcContext.getInstance();
        context.putContext(TENANTID, CAFContext.current.getTenantId());
        return context;
    }

    @Override
    public void replay(RpcContext newContext) {
        ICAFContextService service = SpringBeanUtils.getBean(ICAFContextService.class);
        var tenantId = (Integer)newContext.getContext(TENANTID);
//        var checktenantid = newContext.getContext(CHECK_CURRENT_TENANTID)==null?true:(boolean)newContext.getContext(CHECK_CURRENT_TENANTID);
        if (tenantId != null) {
            RequestTenantContextHolder.set(new RequestTenantContextInfo(tenantId));
//            if(checktenantid && tenantId != service.getTenantId()){
//                RequestTenantContextHolder.set(new RequestTenantContextInfo(tenantId));
//            }else if(!checktenantid){
//                RequestTenantContextHolder.set(new RequestTenantContextInfo(tenantId));
//            }
        }
    }

    @Override
    public void restore(RpcContext newContext) {
        var tenantId = (Integer)newContext.getContext(TENANTID);
        if (tenantId != null) {
            RequestTenantContextHolder.restore();
        }
    }
}
